package com.wlz.utils;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;

/**
 * 文件上传工具类
 * 
 * @author zyc
 * @date May 16, 2018
 * 
 */
public class UploadUtils {
	/**
     * 保存文件，直接以multipartFile形式
     * @param multipartFile
     * @param path 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile,String path) throws IOException {
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
        byte[] bs = new byte[1024];
        int len;
        while ((len = fileInputStream.read(bs)) != -1) {
            bos.write(bs, 0, len);
        }
        bos.flush();
        bos.close();
        return fileName;
    }
    

    /**
     * 下载网络图片并保存到服务器
     * @param savePath 文件保存绝对路径
     * @return 返回文件名
     * @throws IOException
     */
	public static String download(String urlString, String savePath) throws Exception {
		String filename="";
		try {
			// 构造URL
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			// 设置请求超时为5s
			con.setConnectTimeout(5 * 1000);
			
			// 输入流
			InputStream is = con.getInputStream();

			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			filename=UUID.randomUUID().toString().replaceAll("-", "")+".jpg";
			OutputStream os = new FileOutputStream(sf.getPath() + File.separator + filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
		} catch (Exception e) {
			filename="";
			e.printStackTrace();
		}
		return filename;
	}


	/**
	 * cos 上传
	 * @param request
	 * @param path
	 * @param secretId
	 * @param secretKey
	 * @return
	 * @throws Exception
	 */
	public static String uploadFile(HttpServletRequest request, String path, String secretId, String secretKey) throws Exception {
		String realpath = null;
		MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request,
				MultipartHttpServletRequest.class);
		MultipartFile file = null;
		if (multipartRequest != null) {
			file = multipartRequest.getFile("file");
		}
		if (file != null) {
			realpath = CosUtils.uploadInputStreamChangeToImageToCos(file.getInputStream(), MessageCodeUtils.getCode(), secretId, secretKey, path);
		}

		return realpath;
	}

}
